package com.kehutong.auth.controller;

import com.kehutong.auth.entity.SmsCode;
import com.kehutong.auth.service.SmsCodeService;
import com.kehutong.common.DoveClient;
import com.kehutong.common.util.Token;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.util.Objects;
import org.coraframework.util.time.TimeUtil;


/**
 * 授权登录
 *
 * @author: liukunlong
 * @date: 2021-03-25 19:19
 */
@MvcAction
@ReqMapping("/admin/sms")
public class SmsController {

    private static Logger logger = LoggerFactory.getLogger(SmsController.class);


    @Inject
    private SmsCodeService smsCodeService;
    @Inject
    private DoveClient doveClient;

    // 发送短信
    @ReqMapping("/sendsms")
    public Object sendsms(Token token, String mobile) throws Exception {
        return smsCodeService.send(token, mobile);
    }

    // 短信验证
    @ReqMapping("/checkSmsCode")
    public Object checkSmsCode(Token token, String code) throws Exception {
        return smsCodeService.checkSmsCode(token.getSessionId(), code);
    }

    // 解散企业
    @ReqMapping("/dissolve")
    public Object dissolve(Token token, String code) throws Exception {
        SmsCode smsCode = smsCodeService.find(token.getSessionId(), code);

        if (Objects.isNull(smsCode)) {
            return Result.error(0, "验证码错误");
        }

        long s = (TimeUtil.timeMillis() - smsCode.getCreateTime().getTime()) / (1000 * 60);
        if (s > 3) {
            return Result.error(0, "验证码已超时");
        }

        JSONObject result = doveClient.post("/admin/service/corp/delete", (http) -> {
            http.addParam("id", token.getCompanyNo());
        });
        if (result.getIntValue("code") != 200) {
            return Result.error(0, result.getString("message"));
        }

        doveClient.post("/kht-bin/session/service/batch/logout", (http) -> {
            http.addParam("companyNo", token.getCompanyNo());
        });

        return Result.success();
    }
    
}
